package com.example.reader.ui.read.view;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;

import com.blankj.utilcode.utils.ConvertUtils;
import com.blankj.utilcode.utils.StringUtils;
import com.example.reader.SPReadInfo;
import com.example.reader.ui.read.presenter.FileHandler;

import java.io.UnsupportedEncodingException;
import java.util.Vector;

import static com.example.reader.SPReadInfo.TEXT_COLOR;
import static com.example.reader.SPReadInfo.TEXT_SIZE;

/**
 * Created by Administrator on 2017/3/15.
 */

public class BookDrawHelper {
    private static final String TAG = "BookDrawHelper";

    public String charSet = "gbk";

    private final Context context;
    private final long fileLength;
    private int pageStart = 0;
    private int pageEnd = 0;
    int contentWidth;
    int contentHeight;
    private int textSize;
    int lineSpace;
    String textColor;
    private Paint textPaint;
    private final FileHandler handler;

    public BookDrawHelper(Context context, int contentWidth, int contentHeight) {
        this.context = context;
        this.contentWidth = contentWidth;
        this.contentHeight = contentHeight;
        String filePath = context.getExternalCacheDir() + "/xcb.txt";
        handler = new FileHandler(filePath);
        fileLength = handler.getFileLength();
        init();
        initPaint();
    }

    private void init() {
        SharedPreferences preferences = context.getSharedPreferences(SPReadInfo.SP_NAME, Context.MODE_WORLD_READABLE);
        int textsp = preferences.getInt(TEXT_SIZE, 14);
        textSize = ConvertUtils.sp2px(textsp);
        lineSpace = textSize / 5 * 3;
        textColor = preferences.getString(TEXT_COLOR, "#FFFFFF");
    }

    private void initPaint() {
        textPaint = new Paint();
        textPaint.setTextSize(textSize);
        textPaint.setColor(Color.parseColor(textColor));
    }

    public void drawBeforePage(Canvas canvas) {
        Vector<String> beforeText = pageUp();
        Log.i(TAG, "drawBeforePage: " + beforeText.toString());
        int textY = textSize;
        for (String s : beforeText) {
            canvas.drawText(s, 0, textY, textPaint);
            textY += textSize + lineSpace;
        }
    }

    public void drawCurrentPager(Canvas canvas) {
        Vector<String> strings = pageDown();
        int textY = textSize;
        for (String s : strings) {
            canvas.drawText(s, 0, textY, textPaint);
            textY += textSize + lineSpace;
        }
        Log.i(TAG, "->drawCurrentPager:text=" + strings.toString());
    }

    /**
     * 下一页
     *
     * @param canvas
     */
    public void drawNextPage(Canvas canvas) {
        Vector<String> strings = pageDown();
        int textY = textSize;
        for (String s : strings) {
            canvas.drawText(s, 0, textY, textPaint);
            textY += textSize + lineSpace;
        }
        Log.i(TAG, "->drawNextPage: text=" + strings.toString());
    }

    public Vector<String> pageUp() {
        Vector<String> strings = new Vector<>();
        int textY = textSize;
        int readStart = pageStart;
        while (textY < contentHeight) {
            // 如果是开始角标是零就不往前度了
            if (readStart <= 0) {
                break;
            }
            byte[] bytes = handler.readParagraphBefore(readStart);
            readStart = readStart - bytes.length;// 往前度 减去本次读到的长度
            try {
                //byte 数组转换string 并替换 换行符号
                String aPart = new String(bytes, charSet).replaceAll("\\r\\n", "");
                if (StringUtils.isEmpty(aPart)) {
                    continue;
                }
                //储存当前段落的每一行文字
                Vector<String> paragraph = new Vector<>();
                while (!StringUtils.isEmpty(aPart)) {
                    int lineCount = textPaint.breakText(aPart, true, contentWidth, null);
                    String lineText = aPart.length() > lineCount ? aPart.substring(0, lineCount) : aPart;
                    aPart = aPart.length() > lineCount ? aPart.substring(lineCount) : "";
                    paragraph.add(lineText);
                }
                //把当前段落显示在屏幕上，（应为是度上一页所以倒着取集合内容）
                while (textY < contentHeight && paragraph.size() > 0) {
                    String lineText = paragraph.get(paragraph.size() - 1);
                    strings.add(0, lineText);
                    paragraph.remove(lineText);
                    textY += textSize + lineSpace;
                }

                //如果当前段落屏幕没有显示完 算出剩余的长度，重新计算的开始角标的位置
                String renainText = "";
                while (paragraph.size() > 0) {
                    renainText += paragraph.get(0);
                    paragraph.remove(0);
                }
                readStart = readStart + renainText.getBytes(charSet).length;

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        pageEnd = pageStart;
        pageStart = readStart;
        Log.e(TAG + "->pageUp：", "pagestart=" + pageStart + ",pageend=" + pageEnd);
        return strings;
    }


    private Vector<String> pageDown() {
        Vector<String> strings = new Vector<>();
        int textY = textSize;
        // 从上一次结束位置 + 1 的地方开始读（上次读到[1024],现在就应该从[1025]开始读）
        pageStart = pageEnd;
        int readStart = pageStart;
        while (textY < contentHeight) {
            byte[] bytes = handler.readParagraphForward(readStart);
            try {
                readStart = readStart + bytes.length;
                String aPart = new String(bytes, charSet).replaceAll("\\r\\n", "");
                if (StringUtils.isEmpty(aPart)) {
                    continue;
                }
                //储存当前段落的每一行文字
                Vector<String> paragraph = new Vector<>();
                while (!StringUtils.isEmpty(aPart)) {
                    int lineCount = textPaint.breakText(aPart, true, contentWidth, null);
                    String lineText = aPart.length() > lineCount ? aPart.substring(0, lineCount) : aPart;
                    aPart = aPart.length() > lineCount ? aPart.substring(lineCount) : "";
                    paragraph.add(lineText);
                }

                //把当前段落显示在屏幕上，（应为是度上一页所以倒着取集合内容）
                while (textY < contentHeight && paragraph.size() > 0) {
                    String lineText = paragraph.get(0);
                    strings.add(lineText);
                    paragraph.remove(lineText);
                    textY += textSize + lineSpace;
                }

                //如果当前段落屏幕没有显示完 算出剩余的长度，重新计算的开始角标的位置
                if (paragraph.size() > 0) {
                    String remainText = "";
                    while (paragraph.size() > 0) {
                        remainText += paragraph.get(0);
                        paragraph.remove(0);
                    }
                    //TODO 待优化 "\\r"
                    readStart = readStart - (remainText + "\\r").getBytes(charSet).length;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        pageEnd = readStart;
        Log.i(TAG, "pageDown: pagestart=" + pageStart + ",,pageend=" + pageEnd);
        Log.i(TAG, "pageDown: strings=" + strings.toString().replaceAll(",", "\\n"));
        return strings;
    }

}
